package com.hq.door.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.ResourceBundle;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.w3c.dom.Document;

import com.hq.door.bean.WeChatEventData;
import com.hq.door.bean.WeChatReturnData;
import com.hq.door.service.IWeChatService;
import com.hq.door.service.impl.WeChatServiceImpl;
import com.hq.door.util.Sha1Util;

@Controller
@RequestMapping("/weChat")
public class WeChatSController {

	@Autowired
	IWeChatService weChatService;

	@RequestMapping(value = "/checkSignatureAndEventHandle", method = RequestMethod.GET)
	@ResponseBody
	public String checkSignature(String signature, String timestamp,
			String nonce, String echostr) throws IOException {

		ResourceBundle resource = ResourceBundle.getBundle("weChat-cfg");
		String token = resource.getString("token");

		String tmpArr[] = { token, timestamp, nonce };

		Arrays.sort(tmpArr);

		String tmpStr = tmpArr[0] + tmpArr[1] + tmpArr[2];

		String sha1Str = Sha1Util.getSha1(tmpStr);

		if (sha1Str.equals(signature)) {
			return echostr;
		} else {
			return "";
		}
	}

	@RequestMapping(value = "/checkSignatureAndEventHandle", method = RequestMethod.POST, produces = "application/xml;charset=UTF-8")
	@ResponseBody
	public Object EventHandle(@RequestBody WeChatEventData weChatEventData)
			throws TransformerException {
		System.out.println(weChatEventData);
		WeChatReturnData weChatReturnData = new WeChatReturnData();
		weChatReturnData.setToUserName(weChatEventData.getFromUserName());
		weChatReturnData.setFromUserName(weChatEventData.getToUserName());
		weChatReturnData.setCreateTime(System.currentTimeMillis()*1000);
		weChatReturnData.setMsgType("text");
		weChatReturnData.setContent("欢迎您，请点击下方按钮使用相应功能");
		if("text".equals(weChatEventData.getMsgType())){
			return weChatReturnData;
		}
		if("event".equals(weChatEventData.getMsgType())&&"subscribe".equals(weChatEventData.getEvent())){
			return weChatReturnData;
		}
		return "";
	}
//	public Object EventHandle(@RequestBody DOMSource message)
//			throws TransformerException {
//
//		StringWriter writer = new StringWriter();
//		StreamResult result = new StreamResult(writer);
//		TransformerFactory tf = TransformerFactory.newInstance();
//		Transformer transformer = tf.newTransformer();
//		transformer.transform(message, result);
//		System.out.println(writer.toString());
//
//		return "";
//	}

	@RequestMapping("/wechatDispatcher")
	public String wechatDispatcher(@RequestParam(required=true) String code,@RequestParam(required=true) String state,
			HttpSession session) {
		if (code != null) {
			String openid = weChatService.getWebAccessToken(code);
			if (!"".equals(openid)) {
				session.setAttribute("wexinId", openid);
				switch (state) {
				case "0":
					return "redirect:/StudentFront/weChatCheck";
				case "1":
					return "redirect:/front/teacher/weChatCheck";
				case "2":
					return "redirect:/front/parent/weChatCheck";
				default:
					break;
				}
			}
		}

		return null;
	}
}
